<?php
/**
 *      [迷你云] (C)2009-2012 南京恒为网络科技.
 *   软件仅供研究与学习使用，如需商用，请访问www.miniyun.cn获得授权
 * 
 */
?>
<?php

class OperateController extends CUserController
{

    
    public function actionIndex()
    {
        $ct    = Yii::app()->request->getParam('ct','-1');
        $ac    = Yii::app()->request->getParam('ac','-1');
        $cname = Yii::app()->request->getParam('cname','-1');
        $pid   = Yii::app()->request->getParam('pid','-1');
        $aid   = Yii::app()->request->getParam('aid','-1');
        $cid   = Yii::app()->request->getParam('cid','-1');           $tid   = Yii::app()->request->getParam('tid','-1');   

        if ($ct == "-1" || $ac == "-1"){
            echo CJSON::encode(CUtils::retMessage(false, 0, "传入参数错误"));;
            Yii::app()->end();
        }

        $user = Yii::app()->session["user"];
        $userId = $user["id"];

        if ($ct=="dir" && $ac == "add"){                   $this->addFolder($userId, $cname, $pid, $aid);
        }elseif ($ct=="file" && $ac == "delete"){              $this->delete($userId, $cid, $tid);
        }elseif ($ct=="file" && $ac == "edit"){              $this->editFile($userId);
        }elseif ($ct=="dir" && $ac == "get"){              $this->getTreelist($userId);
        }elseif ($ct=="dir" && $ac == "edit"){              $this->editFolder($userId, $cid, $cname);
        }elseif ($ct=="file" && $ac == "get"){              $this->getdetail($userId);
        }elseif ($ct=="file" && $ac == "move"){              $this->moveFile($userId);
        }elseif ($ct=="file" && $ac == "copy"){              $this->copy($userId);
        }elseif ($ct=="dir" && $ac == "move_dir"){              $this->moveFolder($userId);
        }elseif ($ct=="rb" && $ac == "get_num"){              $this->rbCount($userId);
        }elseif ($ct=="file" && $ac == "star"){              $this->star($userId);
        }elseif ($ct=="rb" && $ac == "revert"){              $this->rbRevert($userId);
        }elseif ($ct=="rb" && $ac == "del"){              $this->rbDelete($userId);
        }elseif ($ct=="rb" && $ac == "clean"){              $this->rbClean($userId);
        }elseif ($ct=="ajax_user" && $ac == "get_space_info"){              $this->getSpaceSize($userId);
        }elseif ($ct=="pickcode" && $ac == "download"){              $this->download($userId);
        }elseif ($ct=="app" && $ac == "get_online_img"){              $this->getOnlineImg($userId);
        }else {
            echo CJSON::encode(CUtils::retMessage(false, 0, "传入参数错误"));
            Yii::app()->end();
        }
        
    }
    
    
    private function getOnlineImg($userId){
        $tid         = Yii::app()->request->getParam('tid',-1);          $cid         = Yii::app()->request->getParam('cid',0);          $limit       = Yii::app()->request->getParam('limit', 45);          $start       = Yii::app()->request->getParam('s', 0);
        $ids         = Yii::app()->request->getParam('ids');
        
        $dom = new DOMDocument('1.0', 'utf-8');
        $data = $dom->appendChild($dom->createElement('data'));
        
        if (empty($ids)) {
                        $files = UserFile::model()->getUserFolderImg($userId, $cid, $start, $limit);
        } else {
                        $files = $list = UserFile::model()->getUserLocationImg($userId, $limit, $start, $ids);
        }
        
        foreach ($files as $file) {
            $list = $data->appendChild($dom->createElement('list'));
            if ($tid == $file["id"]){
                $list->setAttribute('selected', 1);
            }else {
                $list->setAttribute('selected', 0);
            }
            $filePath = CUtils::pathinfo_utf($file['file_name']);
            $list->setAttribute('type', $filePath["extension"]);
            
            $downUrl    = Yii::app()->params['app']['host']."/index.php?r=operate/index&ct=pickcode&ac=download&pickcode=".$file["id"];
            $thumSmall  = Yii::app()->params['app']['host']."/index.php?r=thumbnail/index&size=normal&tid=".$file["id"]."&ver=".$file['version_id'];
            $thumLarge  = Yii::app()->params['app']['host']."/index.php?r=thumbnail/index&size=large&tid=".$file["id"]."&ver=".$file['version_id'];
            
            
            $url = $dom->createElement('url');
            $urlText = $dom->createTextNode($downUrl);
            $url->appendChild($urlText);
            
            $midUrl = $dom->createElement('mid_url');
            $midUrlText = $dom->createTextNode($downUrl);
            $midUrl->appendChild($midUrlText);
            
            $icon = $dom->createElement('icon');
            $iconText = $dom->createTextNode($thumSmall);
            $icon->appendChild($iconText);
            
            $sourceUrl = $dom->createElement('source_url');
            $sourceUrlText = $dom->createTextNode($downUrl);
            $sourceUrl->appendChild($sourceUrlText);
            
            $list->appendChild($url);
            $list->appendChild($midUrl);
            $list->appendChild($icon);
            $list->appendChild($sourceUrl);
        }
        header('Content-Type: text/xml;');
        $xmlString = $dom->saveXML();
        echo $xmlString;
        Yii::app ()->end ();
    }
    
   
    private function rbClean($userId){
        $trash = new Trash();
        $trash->_userId = $userId;
        $trash->invoke(Trash::CLEAN);
        $trash->handleEnd();
    }
    
   
    private function rbDelete($userId){
        $tids  = Yii::app()->request->getParam('tid',-1);
        
    	if ($tids == "-1"){
            echo CJSON::encode(CUtils::retMessage(false, 0, "传入参数错误"));;
            Yii::app()->end();
        }
        
        $trash = new Trash();
        $trash->_userId = $userId;
        $trash->fromIds = $tids;
        $trash->invoke(Trash::DELETE);
        $trash->handleEnd();
    }
    
   
    private function rbRevert($userId){
        $tids  = Yii::app()->request->getParam('tid',-1);
        
    	if ($tids == "-1"){
            echo CJSON::encode(CUtils::retMessage(false, 0, "传入参数错误"));
            Yii::app()->end();
        }
        
        $trash = new Trash();
        $trash->_userId = $userId;
        $trash->fromIds = $tids;
        $trash->invoke(Trash::REVERT);
        $trash->handleEnd();
    }
    
    
    
    private function download($userId){
        $pickcode         = Yii::app()->request->getParam('pickcode',-1);
        if ($pickcode == -1){
            $this->redirect(array("netdisk/index"));
        }

        $downLoad = new DownLoad();
        $downLoad->_userId = $userId;
        $downLoad->fileId = $pickcode;
        try {
            $downLoad->invoke();
        } catch (ApiException $e) {
            $downLoad->result["state"] = false;
        }
        
        if ($downLoad->result["state"] == false) {
            $this->redirect(array("netdisk/index"));
        }
    }

    
    private function star($userId){
        $tid         = Yii::app()->request->getParam('tid',-1);
        $is_star     = Yii::app()->request->getParam('is_star',0);
        
    	if ($tid == "-1"){
            echo CJSON::encode(CUtils::retMessage(false, 0, "传入参数错误"));;
            Yii::app()->end();
        }
        
        $fileStar = FileStar::model()->find("user_id=? and file_id=?",array($userId,$tid));
        if (!empty($fileStar)){
            if ($is_star == 0){
                FileStar::model()->deleteByPk($fileStar['id']);
            }
        }else {
            if ($is_star == 1){
                $fileStar = new FileStar();
                $fileStar['user_id'] = $userId;
                $fileStar['file_id'] = $tid;
                $fileStar->save();
            }
        }

        $ret = array();
        $ret['state']   = 1;
        echo CJSON::encode($ret);
        Yii::app()->end();
    }

    
    private function copy($userId){
        $tid     = Yii::app()->request->getParam('tid','-1');
        $_cid    = Yii::app()->request->getParam('_cid','-1');

        if ($tid == "-1" || $_cid == "-1"){
            echo CJSON::encode(CUtils::retMessage(false, 0, "传入参数错误"));;
            Yii::app()->end();
        }
        $ids = array_slice(explode(',', $tid), 0);
        $copy = new Copy();
        foreach ($ids as $id) {
            $copy->_userId = $userId;
            $copy->toId = $_cid;
            $copy->fromId = $id;
            try {
                $copy->invoke(false);
            } catch (ApiException $e) {
                $copy->result["data"][$id] = false;
            }
        }
        $copy->handleEnd();
    }


    
    private function editFolder($userId){
        $cid   = Yii::app()->request->getParam('cid','-1');
        $cname = Yii::app()->request->getParam('cname',null);

        $state = Array();
        $state['state'] = false;
        $state['msg_code'] = -1;
        if ($cid == "-1" || $cname == null){
            $state['msg'] = "参数不能为空";
            echo CJSON::encode($state);
            Yii::app()->end();
        }
                                if (CUtils::checkNameInvalid($cname) != 0) {
            $state['msg'] = "命名不能包含下列字符串： ^|?*\\<\":>";
            echo CJSON::encode($state);
            Yii::app()->end();
        }
        
        $file = UserFile::model()->findByAttributes(array('id'=>$cid,'is_deleted' => 0, 'user_id' => $userId));
        if (!$file) {
            $state['msg'] = "参数不能为空";
            echo CJSON::encode($state);
            Yii::app()->end();
        }

        $tid = $file['parent_file_id'];
        $fromPath = $file['file_path'];
        $pathInfo = CUtils::pathinfo_utf($fromPath);
        $toPath   = $pathInfo["dirname"]. "/" . $cname;
        $toPath = CUtils::convertStandardPath($toPath);

        $move = new Move();
        $move->_userId = $userId;
        $move->toId   = $tid;
        $move->fromId = $cid;
        $move->fromPath = $fromPath;
        $move->toPath   = $toPath;
        $move->invoke();
        $result = $move->result;
        if ($result['state'] == false) {
            $move->handleEnd();
        } else {
            $state['msg']   = "重命名成功";
            $state['state'] = true;
            $state['aid']   = 1;
            $state['cid']   = $cid;
            $state['cname'] = $cname;
            echo CJSON::encode($state);
            Yii::app()->end();
        }
    }

    
    private function editFile($userId){
        $file_id   = Yii::app()->request->getParam('file_id','-1');
        $file_name = Yii::app()->request->getParam('file_name','-1');

        $state = Array();
        $state['state'] = false;
        $state['msg_code'] = -1;
        if ($file_id == "-1" || $file_name == "-1"){
            $state['msg'] = "参数不能为空";
            echo CJSON::encode($state);
            Yii::app()->end();
        }
                                if (CUtils::checkNameInvalid($file_name) != 0) {
            echo CJSON::encode(CUtils::retMessage(false, 0, "命名不能包含下列字符串： ^|?*\\<\":>"));
            Yii::app()->end();
        }
        
        $file = UserFile::model()->findByAttributes(array('id'=>$file_id,'is_deleted' => 0, 'user_id' => $userId));
        if (!$file) {
            $state['msg'] = "参数不能为空";
            echo CJSON::encode($state);
            Yii::app()->end();
        }

        $tid = $file['parent_file_id'];
        $fromPath = $file['file_path'];
        $pathInfo = CUtils::pathinfo_utf($fromPath);
        $toPath   = $pathInfo["dirname"]. "/" . $file_name;
        $toPath = CUtils::convertStandardPath($toPath);

        $move = new Move();
        $move->_userId = $userId;
        $move->toId   = $tid;
        $move->fromId = $file_id;
        $move->fromPath = $fromPath;
        $move->toPath   = $toPath;
        $move->invoke();
        $result = $move->result;
        $pathInfo = CUtils::pathinfo_utf($move->toPath);
        if ($result['state'] == false) {
            $move->handleEnd();
        } else {
            $data = Array();
            $data['file_name'] = $pathInfo['basename'];
            $state['msg'] = "重命名成功";
            $state['state'] = true;
            $state['msg_code'] = 1;
            $state['data'] = $data;
            echo CJSON::encode($state);
            Yii::app()->end();
        }
    }

    
    private function moveFolder($userId){
        $from_cid  = Yii::app()->request->getParam('from_cid','-1');
        $to_cid    = Yii::app()->request->getParam('to_cid','-1');

        if ($from_cid == "-1" || $to_cid == "-1"){
            echo CJSON::encode(CUtils::retMessage(false, 0, "传入参数错误"));;
            Yii::app()->end();
        }

        $move = new Move();
        $move->_userId = $userId;
        $move->toId = $to_cid;
        $move->fromId = $from_cid;
        $move->invoke(false);
        $result = $move->result;

        if ($result["state"]) {
            $first = Array();
            $first['name'] = "我的文件";
            $first['aid'] = 1;
            $first['cid'] = "1_0";
            $first['pid'] = "0";
            $myFile = array("1_0"=>$first);
            $treeData = array();
            array_push($treeData,$myFile);
            $treeData = UserFile::model()->getAllFolder($userId,$treeData);

            $ret = Array();
            $ret['state'] = true;
            $ret['code']  = 0;
            $ret['msg']  = "重命名成功";
            $ret['data'] = Array();
            $ret['dir']  = $treeData;
            echo CJSON::encode($ret);
            Yii::app()->end();
        } else {
            $move->handleEnd();
        }
    }


    
    private function moveFile($userId){
        $tid     = Yii::app()->request->getParam('tid','-1');
        $_cid    = Yii::app()->request->getParam('_cid','-1');

        if ($tid == "-1" || $_cid == "-1"){
            echo CJSON::encode(CUtils::retMessage(false, 0, "传入参数错误"));;
            Yii::app()->end();
        }
        
        $ids = array_slice(explode(',', $tid), 0);
        $move = new Move();
        foreach ($ids as $id) {
            $move->_userId = $userId;
            $move->toId   = $_cid;
            $move->fromId = $id;
            try {
                $move->invoke(false);
            } catch (ApiException $e) {
                $move->result["data"][$id] = false;
            }
        }
        $move->handleEnd();
    }

    
    private function rbCount($userId){
        $fileHandle = new TrashList();
        $retval = Array();
        $retval["count"] = $fileHandle->trashCount($userId);
        echo CJSON::encode($retval);
        Yii::app()->end();
    }

    
    private function getSpaceSize($userId){
        $total =  CUtils::totalSize($userId);
        $used  =  UserFile::model()->getUsedSpace($userId);

        $usedSpace = 0;
        if (count($used) > 0){
            $usedSpace = $used[0]["usedSpace"];
        }


        $data = Array();
        $data['total'] = $total;
        $data['used']  = $usedSpace;
        
        $ret = Array();
        $ret["1"] = $data;
        
        echo CJSON::encode($ret);
        Yii::app()->end();
    }

    
    private function getdetail($userId){
        $cid   = Yii::app()->request->getParam('cid','-1');
        $tid   = Yii::app()->request->getParam('tid','-1');
        
        if ($cid == -1 && $tid != -1){
            $id = $tid;
        }elseif ($cid != -1 && $tid == -1){
            $id = $cid;
        }else {
            echo CJSON::encode(CUtils::retMessage(false, 0, "传入参数错误"));;
            Yii::app()->end();
        }
        
        $file = UserFile::model()->findByPk($id);

        $ret = Array();
        if (empty($file)){
            $ret['state']     = false;
            $ret['msg']       = "获取信息失败";
            $ret['msg_code']  = -1;
            echo CJSON::encode($ret);
            Yii::app()->end();
        }
        $data = Array();
        if ($file['file_type'] == 0){
            $data['file_id']        = $file['id'];
            $data['user_id']               = $file['user_id'];
            $data['file_name']           = $file['file_name'];
            $data['file_size']            = $file['file_size'];
            $data['file_tag']              = "";
            $data['file_description']        = "";
            $data['file_type']        = 125;
            $data['user_ip']        = "2045082730";
            $data['user_ip']        = "2045082730";
            $data['ptime']      = date('Y-m-d',strtotime($file['created_at']));
            $data['utime']      = date('Y-m-d',strtotime($file['updated_at']));
            $data['pick_code']      = "";
            $data['pick_code_old']      = "";
            $data['pick_time']      = date('Y-m-d',strtotime($file['updated_at']));
            $data['download_count']      = "0";
            $data['is_share']      = "0";
            $data['category_id']      = $file['parent_file_id'];
            $data['area_id']      = "1";
            $data['file_status']      = "1";
            $data['file_name_sort']      = "573351";
            $data['is_mark']      = "0";
            $data['file_question']      = "";
            $data['file_answer']      = "";
            $data['is_collect']      = "";
        }else{
            $data['category_id']        = $file['id'];
            $data['area_id']              = "1";
            $data['parent_id']           = $file['parent_file_id'];
            $data['user_id']               = $file['user_id'];
            $data['category_name']        = $file['file_name'];
            $data['category_desc']        = "";
            $data['category_cover']       = "";
            $data['category_file_count']  = UserFile::model()->getFileCount($file['id']);
            $data['category_order']  = 0;
            $data['pick_code']      = "";
            $data['password']      = "";
            $data['ptime']      = date('Y-m-d',strtotime($file['created_at']));
            $data['utime']      = date('Y-m-d',strtotime($file['updated_at']));
            $data['ext1']      = "";
            $data['ext2']      = "";
            $data['ext3']      = "";
        }

        $ret = Array();
        $ret['state']     = true;
        $ret['msg']       = "获取信息成功";
        $ret['msg_code']  = 1;
        $ret['data']      = $data;
        echo CJSON::encode($ret);
        Yii::app()->end();
    }


    
    private function addFolder($userId, $cname, $pid, $aid){
        if (strpos($pid, "_")){
            $pid  = 0;
        }
                                if (CUtils::checkNameInvalid($cname) != 0) {
            $state['msg'] = "命名不能包含下列字符串： ^|?*\\<\":>";
            echo CJSON::encode($state);
            Yii::app()->end();
        }
        $createFolder = new CreateFolder();
        $createFolder->_userId   = $userId;
        $createFolder->cname     = $cname;
        $createFolder->_parentId = $pid;
        $createFolder->aid       = $aid;
        $createFolder->invoke();
        $createFolder->handleEnd();
    }


    
    private function delete($userId, $cid, $tid){

        if ($cid == "-1" && $tid != "-1"){
            $fileIdStr = $tid;
        }elseif ($cid != "-1" && $tid == "-1"){
            $fileIdStr = $cid;
        }elseif ($cid != "-1" && $tid != "-1") {
            $fileIdStr = $cid . "," . $tid;
        }else {
            $state = CUtils::retMessage(false, 0, "参数错误");
            echo CJSON::encode($state);
            Yii::app()->end();
        }

        $del = new Delete();
        $del->_userId = $userId;
        $del->invoke($fileIdStr);
        $del->handleEnd();
    }
    

    
    private function getTreelist($userId){
        $tree = new FileList();
        $treeData = $tree->getFoderTree($userId);

        echo $treeData;
        Yii::app()->end();
    }
}